<script setup lang="ts">
import store from '@/store'
import { numberToChinese } from '@/utils/tools'
import { createVNode, h, reactive, ref, nextTick } from 'vue'
import { ExclamationCircleFilled, PlusOutlined } from '@ant-design/icons-vue'
import { Modal } from 'ant-design-vue'
import IconFont from '@/components/IconFont/index.vue'
import VisibleRender from '@/components/VisibleRender/index.vue'
import draggable from 'vuedraggable'

const modal = reactive({
  open: false,
  type: 'save',
  allowUpdate: true,
  loading: false,
  title: '新建问卷'
})

const formState = reactive({
  id: '',
  // 功能分类名称
  moduleCategory: '',
  templateName: '',
  templateCode: '',
  templateType: '',
  cardTitle: '',
  cardContent: '',
  cardFormData: [],
  cardButtons: []
})

const teamplateTypeChange = (e) => {
  console.log(e)
  if (e === '数据展示') {
    formState.cardFormData = []
  } else {
    formState.cardFormData = [
      {
        name: '',
        id: 'A-1',
        type: '输入',
        sort: '',
        value: '',
        inputText: '',
        inputMode: '',
        rules: null,
        config: null,
        options: [],
        exc: ''
      }
    ]
  }
}

const answertype = [
  {
    label: '单选',
    value: '单选'
  },
  {
    label: '多选',
    value: '多选'
  },
  {
    label: '输入',
    value: '输入'
  },
  {
    label: '单选+输入',
    value: '单选+输入'
  },
  {
    label: '多选+输入',
    value: '多选+输入'
  },
  {
    label: '数字选择',
    value: '数字选择'
  },
  {
    label: '搜索输入',
    value: '搜索输入'
  },
  {
    label: '日期时间选择',
    value: '日期时间选择'
  }
]

const formState_reset = () => {
  Object.assign(formState, {
    id: '',
    // 功能分类名称
    moduleCategory: '',
    templateName: '',
    templateCode: '',
    templateType: '',
    cardTitle: '',
    cardContent: '',
    cardFormData: [],
    cardButtons: [],
    ifVipAuth: 0
  })
}

const subitemTypeChange = (e, item) => {
  if (e === '输入' || !e) {
    item.options = []
  } else {
    item.options = [
      {
        id: 0,
        key: '',
        value: '',
        input: false,
        maxlength: 50
      }
    ]
  }
  if (e === '数字选择') {
    item.config = {
      min: '',
      max: '',
      min_label: '',
      max_label: ''
    }
  } else if (e === '搜索输入') {
    item.config = {
      url: '',
      key: ''
    }
  } else {
    item.config = null
  }
}

const moveOptions = (list, item) => {
  console.log('拖拽结束')
}

const del = (index, item) => {
  item.splice(index, 1)
}

const delTwo = (index, item) => {
  Modal.confirm({
    title: '删除',
    icon: createVNode(ExclamationCircleFilled, {
      style: {
        color: 'var(--color--danger)'
      }
    }),
    content: '确认是否删除',
    okText: '确定',
    okButtonProps: {
      danger: true,
      type: 'primary'
    },
    cancelText: '取消',
    onOk() {
      console.log('OK')
      item.splice(index, 1)
    },
    onCancel() {
      console.log('Cancel')
    }
  })
}

const changes = (index, item, num) => {
  //   console.log(item[index].score)
  const regex = /^([0-9]|[1-9]\d|99)$/
  if (!regex.test(item[index].score)) {
    // 如果输入值不符合规定的1到99的整数，则将inputValue重置为上一个合法的值
    if (Number(item[index].score) > 99) {
      item[index].score = 99
    } else {
      item[index].score = 0
    }
    // item[index].score = item[index].score.substring(0, item[index].score.length - 1)
    // item[index].score = 0
  } else {
    // 如果输入值符合规定的1到99的整数，则更新inputValue
    // item[index].score = item[index].score
  }
}
const addOptions = (item) => {
  const indexs = item.map((v) => {
    return v.id
  })
  let i = 0
  while (indexs.includes(i)) {
    i++
  }
  console.log(i)

  item.push({
    id: i,
    key: '',
    value: '',
    input: false,
    maxlength: 50
  })
}

const elementChecked = (value, subitem) => {
  subitem.options.map((v, index) => {
    if (value === index) {
      v.value = '其他'
      v.disabled = true
      v.input = true
    } else {
      if (v.disabled) {
        v.value = ''
      }
      v.disabled = false
      v.input = false
    }
  })
}

const addSubitem = (module) => {
  let index = 1
  while (module.some((v) => v.id === 'A-' + index)) {
    index++
  }
  module.push({
    name: '',
    id: 'A-' + index,
    type: '输入',
    sort: '',
    value: '',
    inputText: '',
    inputMode: '',
    rules: null,
    config: null,
    options: [],
    exc: ''
  })
}

const addButtons = (list) => {
  list.push({
    buttonType: 'jump',
    buttonDesc: '',
    buttonUrl: ''
  })
}

const sorts = [
  'A',
  'B',
  'C',
  'D',
  'E',
  'F',
  'G',
  'H',
  'I',
  'J',
  'K',
  'L',
  'M',
  'N',
  'O',
  'P',
  'Q',
  'R',
  'S',
  'T',
  'U',
  'V',
  'W',
  'X',
  'Y',
  'Z'
]

const subitem_check = async (_, value) => {
  if (value.type) {
    if (!value.name) {
      return Promise.reject('请输入问题描述')
    }
    if (['单选', '单选+输入', '多选', '多选+输入'].includes(value.type)) {
      const f = value.options.some((v) => {
        return v.value && v.key
      })
      if (!f) {
        return Promise.reject('请完善至少一个问题选项')
      }
      if (value.type.includes('+输入')) {
        const f2 = value.options.some((v) => {
          return v.input
        })
        if (!f2) {
          return Promise.reject('添加输入框需勾选')
        }
      }
    }
  } else {
    return Promise.reject('请选择问题类型')
  }
  return Promise.resolve()
}

const modelForm = ref(null)

const init = (item) => {
  modelForm.value?.clearValidate()
  formState.formData = []
  nextTick(() => {
    if (item) {
      Object.assign(formState, item)
      modal.title = '编辑模板'
      modal.type = 'update'
      modal.open = true
    } else {
      formState_reset()
      modal.allowUpdate = true
      modal.title = '新建模板'
      modal.type = 'save'
      modal.open = true
    }
  })
}

const modalConfirm = () => {
  modelForm.value
    .validate()
    .then(() => {
      modal.loading = true
      console.log('formState', formState)
      emit('onConfirm', {
        data: formState,
        success: () => {
          console.log('success')
          modal.loading = false
          modal.open = false
        },
        fail: () => {
          console.log('fail')
          modal.loading = false
        },
        type: modal.type
      })
    })
    .catch((e) => {
      console.log(e)
      modelForm.value.scrollToField(e.errorFields[0].name, {
        behavior: 'smooth',
        block: 'center'
      })
    })
}

const emit = defineEmits(['onConfirm'])

defineExpose({
  init
})
</script>

<template>
  <a-modal
    width="720px"
    :bodyStyle="store.userStore.bodyStyle"
    v-model:open="modal.open"
    :title="modal.title"
    ok-text="确认"
    cancel-text="取消"
    @ok="modalConfirm"
    :maskClosable="false"
  >
    <a-form
      class="modelForm"
      ref="modelForm"
      :colon="false"
      :model="formState"
      :label-col="{ style: { width: '80px' } }"
      labelAlign="left"
    >
      <a-form-item
        label="功能分类"
        :label-col="{ style: { width: '110px' } }"
        name="moduleCategory"
        required
        :rules="{
          required: true,
          message: '功能分类',
          trigger: 'change',
          whitespace: true
        }"
      >
        <a-input
          style="width: 350px"
          v-model:value="formState.moduleCategory"
          autocomplete="off"
          :maxlength="50"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item
        label="功能名称"
        :label-col="{ style: { width: '110px' } }"
        name="templateName"
        required
        :rules="{
          required: true,
          message: '功能名称不能为空',
          trigger: 'change',
          whitespace: true
        }"
      >
        <a-input
          style="width: 350px"
          v-model:value="formState.templateName"
          autocomplete="off"
          :maxlength="50"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item
        label="功能code"
        :label-col="{ style: { width: '110px' } }"
        name="templateCode"
        required
        :rules="{
          required: true,
          message: '功能code不能为空',
          trigger: 'change',
          whitespace: true
        }"
      >
        <a-input
          style="width: 350px"
          v-model:value="formState.templateCode"
          autocomplete="off"
          :maxlength="50"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item label="VIP鉴权" :label-col="{ style: { width: '110px' } }" name="ifVipAuth">
        <a-switch
          v-model:checked="formState.ifVipAuth"
          checked-children="开"
          :checkedValue="1"
          :unCheckedValue="0"
          un-checked-children="关"
        />
      </a-form-item>

      <a-form-item label="卡片标题" :label-col="{ style: { width: '110px' } }" name="cardTitle">
        <a-input
          style="width: 350px"
          v-model:value="formState.cardTitle"
          autocomplete="off"
          :maxlength="50"
          placeholder="请输         入"
        />
      </a-form-item>
      <a-form-item label="卡片内容" :label-col="{ style: { width: '110px' } }" name="cardTitle">
        <a-textarea
          style="width: 350px"
          v-model:value="formState.cardContent"
          placeholder="请输入卡片内容"
          :maxlength="500"
          :rows="2"
        />
      </a-form-item>
      <a-form-item
        label="用途"
        :label-col="{ style: { width: '110px' } }"
        name="templateType"
        required
        :rules="{
          required: true,
          message: '请选择用途',
          trigger: 'change',
          whitespace: true
        }"
      >
        <a-select
          v-model:value="formState.templateType"
          @change="teamplateTypeChange"
          style="width: 120px"
        >
          <a-select-option value="数据展示">数据展示</a-select-option>
          <a-select-option value="数据录入">数据录入</a-select-option>
        </a-select>
      </a-form-item>
      <template v-if="formState.templateType === '数据录入'">
        <a-form-item>
          <a-row class="title">
            <a-col :span="24"> 表单内容 </a-col>
          </a-row>
        </a-form-item>
        <a-form-item
          v-for="(subitem, i) in formState.cardFormData"
          :key="i"
          :name="['cardFormData', i]"
          :rules="{
            validator: subitem_check
          }"
          class="questionItem"
        >
          <visible-render height="100px">
            <a-row class="row">
              <a-col :span="8">
                <a-form-item
                  :label="'问题 ' + Number(i + 1)"
                  :label-col="{ style: { width: '80px' } }"
                >
                  <a-select
                    v-model:value="subitem.type"
                    @change="subitemTypeChange($event, subitem)"
                    style="width: 120px"
                    :getPopupContainer="(triggerNode) => triggerNode.parentNode"
                  >
                    <a-select-option
                      v-for="item in answertype"
                      :key="item.value"
                      :value="item.value"
                      >{{ item.label }}</a-select-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="15">
                <a-row>
                  <a-col :span="11" v-if="subitem.type === '输入'">
                    <a-form-item label="input类型">
                      <a-select style="width: 100px" v-model:value="subitem.inputMode">
                        <a-select-option value="text">文本键盘</a-select-option>
                        <a-select-option value="number">整数键盘</a-select-option>
                        <a-select-option value="idcard">身份证键盘</a-select-option>
                        <a-select-option value="digit">小数点键盘</a-select-option>
                        <a-select-option value="tel">电话键盘</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :span="13">
                    <a-form-item label="额外参数">
                      <a-input
                        style="width: 140px"
                        v-model:value="subitem.exc"
                        autocomplete="off"
                      />
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-col>
              <a-col class="ft" span="1">
                <icon-font
                  v-if="i"
                  style="margin: 0 16px"
                  class="icon icon-del point"
                  type="icon-shanchu"
                  @click="del(i, formState.cardFormData)"
                />
              </a-col>
            </a-row>
            <a-form-item>
              <a-row>
                <a-col :span="24" class="row">
                  <a-textarea
                    style=" width: 100%;margin: 0 16px"
                    v-model:value="subitem.name"
                    placeholder="请输入问题描述"
                    :maxlength="500"
                    :rows="2"
                  />
                </a-col>
              </a-row>
            </a-form-item>
            <template v-if="['单选', '单选+输入', '多选', '多选+输入'].includes(subitem.type)">
              <a-form-item>
                <draggable
                  class="drag"
                  :list="subitem.options"
                  :handle="'.icon-move'"
                  itemKey="id"
                  animation="300"
                  @end="moveOptions($event, subitem)"
                >
                  <template #item="{ element, index }">
                    <a-row class="item row" :gutter="[16, 0]">
                      <a-col>
                        <a-input
                          style="width: 240px"
                          v-model:value="element.key"
                          autocomplete="off"
                          :maxlength="50"
                          :disabled="element.disabled"
                          placeholder="请输入选项描述"
                        />
                      </a-col>
                      <a-col>
                        <icon-font class="icon-move" type="icon-yidong" />
                      </a-col>
                      <a-col>
                        <a-input
                          style="width: 240px"
                          v-model:value="element.value"
                          autocomplete="off"
                          :maxlength="50"
                          :disabled="element.disabled"
                          placeholder="请输入选项code"
                        />
                      </a-col>
                      <a-col class="row" style="flex: 1">
                        <a-radio
                          v-if="subitem.type.includes('+输入')"
                          :checked="element.input"
                          @change="elementChecked(index, subitem)"
                        >
                          添加输入框
                        </a-radio>
                      </a-col>
                      <a-col class="row">
                        <icon-font
                          v-if="index"
                          class="icon-del"
                          type="icon-shanchu"
                          @click="del(index, subitem.options)"
                        />
                        <icon-font
                          v-else
                          class="icon-plus"
                          type="icon-xinzeng"
                          @click="addOptions(subitem.options)"
                        />
                      </a-col>
                    </a-row>
                  </template>
                </draggable>
              </a-form-item>
            </template>
            <template v-else-if="subitem.type === '数字选择'">
              <a-row class="config" :gutter="[16, 0]">
                <a-col :span="12">
                  <a-form-item
                    :name="['cardFormData', i, 'config', 'min']"
                    :rules="{
                      required: true,
                      message: '最小值不能为空',
                      trigger: 'change'
                    }"
                  >
                    <a-input
                      :value="subitem.config.min"
                      autocomplete="off"
                      @input="(e) => (subitem.config.min = e.target.value.replace(/[^0-9]/g, ''))"
                      placeholder="最小值(包含)"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item
                    :name="['cardFormData', i, 'config', 'max']"
                    :rules="{
                      required: true,
                      message: '最大值不能为空',
                      trigger: 'change'
                    }"
                  >
                    <a-input
                      :value="subitem.config.max"
                      autocomplete="off"
                      @input="(e) => (subitem.config.max = e.target.value.replace(/[^0-9]/g, ''))"
                      placeholder="最大值(不含)"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item>
                    <a-input
                      v-model:value="subitem.config.min_label"
                      autocomplete="off"
                      placeholder="最小值文案"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item>
                    <a-input
                      v-model:value="subitem.config.max_label"
                      autocomplete="off"
                      placeholder="最大值文案"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </template>
            <template v-else-if="subitem.type === '搜索输入'">
              <a-row class="config" :gutter="[16, 0]">
                <a-col :span="12">
                  <a-form-item
                    :name="['cardFormData', i, 'config', 'url']"
                    :rules="{
                      required: true,
                      message: '请求地址不能为空',
                      trigger: 'change'
                    }"
                  >
                    <a-input
                      v-model:value="subitem.config.url"
                      autocomplete="off"
                      placeholder="请求地址"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item
                    :name="['cardFormData', i, 'config', 'key']"
                    :rules="{
                      required: true,
                      message: '请求参数名不能为空',
                      trigger: 'change'
                    }"
                  >
                    <a-input
                      v-model:value="subitem.config.key"
                      autocomplete="off"
                      placeholder="参数名"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </template>
          </visible-render>
        </a-form-item>
        <a-form-item style="margin-top: -16px">
          <a-button type="link" :icon="h(PlusOutlined)" @click="addSubitem(formState.cardFormData)"
            >新增问题</a-button
          >
        </a-form-item>
      </template>
      <a-form-item>
        <a-row class="title">
          <a-col :span="24"> 按钮 </a-col>
        </a-row>
      </a-form-item>
      <template v-for="(item, index) in formState.cardButtons" :key="index">
        <a-row>
          <a-col :span="8">
            <a-form-item
              :name="['cardButtons', index, 'buttonDesc']"
              :rules="{
                required: true,
                message: '按钮文案不能为空',
                trigger: 'change'
              }"
            >
              <a-input v-model:value="item.buttonDesc" autocomplete="off" placeholder="按钮文案" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :name="['cardButtons', index, 'buttonType']"
              :rules="{
                required: true,
                message: '按钮类型不能为空',
                trigger: 'change'
              }"
            >
              <a-select v-model:value="item.buttonType" placeholder="请选择按钮类型">
                <a-select-option value="jump">跳转链接</a-select-option>
                <a-select-option value="save">接口地址</a-select-option>
                <a-select-option value="pdf">打开PDF</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :name="['cardButtons', index, 'buttonUrl']"
              :rules="{
                required: true,
                message: '按钮地址不能为空',
                trigger: 'change'
              }"
            >
              <a-input v-model:value="item.buttonUrl" autocomplete="off" placeholder="按钮地址" />
            </a-form-item>
          </a-col>
        </a-row>
      </template>
      <a-form-item>
        <a-button type="link" :icon="h(PlusOutlined)" @click="addButtons(formState.cardButtons)"
          >新增按钮</a-button
        >
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped lang="less">
.modelForm {
  .red {
    color: #f56667;
  }

  .ant-form-item {
    margin-bottom: 15px;

    &.questionItem {
      padding-top: 8px;
      margin-bottom: 16px;
      // background: #f7f8fa;
    }
  }

  .title {
    width: 100%;
    height: 32px;
    font-family: "PingFang SC";
    font-size: 16px;
    font-weight: 500;
    // color: #1d2129;
    line-height: 24px;
  }

  .add {
    width: 648px;
    height: 32px;
    margin: 0 12px;
    font-family: "PingFang SC";
    font-size: 14px;
    font-weight: 400;
    line-height: 22px;
    color: #165dff;
  }

  .icon-plus,
  .icon-del {
    font-size: 16px;
  }

  .icon-plus {
    color: #165dff;
  }

  .icon-del {
    color: #f53f3f;
  }

  .icon-move {
    font-size: 24px;
    line-height: 32px;
    color: #4e5969;
    cursor: move;
  }

  .form-item {
    line-height: 32px;
  }
}

.row {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.drag {
  padding: 0 16px;

  .item:not(:first-child) {
    margin-top: 8px;
  }
}

.config {
  padding: 0 16px;
}

.point {
  cursor: pointer;
}

.row {
  .ft {
    display: flex;
    flex-direction: row-reverse;
    align-items: flex-start;
    height: 47px;

    .icon {
      height: 32px;
      line-height: 32px;
    }
  }
}
</style>
